<?php

namespace App\Trip\Orders\BookOrders\Train;

use App\Models\Train\TrainOrders\Repositories\Interfaces\TrainOrdersRepositoryInterface;
use App\Trip\Orders\BookOrders\Params\AbstractParam\TripParam;
use App\Trip\Orders\BookOrders\Params\Param;
use App\Trip\Orders\BookOrders\Params\PassengersParam;
use Exception;
use Illuminate\Support\Facades\Log;

class CheckTrip
{
    private PassengersParam $passengersParam;
    private TripParam       $trainParam;
    /**
     * @var TrainOrdersRepositoryInterface
     */
    private TrainOrdersRepositoryInterface $trainOrderRepo;
    private ?Param                         $param;

    /**
     * @throws Exception
     */
    public function __construct(TripParam $trainParam, PassengersParam $passengersParam, ?Param $param = null)
    {
        $this->trainParam      = $trainParam;
        $this->param           = $param;
        $this->passengersParam = $passengersParam;
        $this->trainOrderRepo  = app(TrainOrdersRepositoryInterface::class);
        $this->check();
    }

    /**
     * @throws Exception
     */
    public function check(): bool
    {

        // 如果是改签
        if ($this->param) {
            if ($this->param->getBookType()->isChange()) {
                $list = $this->trainOrderRepo
                    ->checkSameTripTrainData([
                        'from_station_code' => $this->trainParam->getFromCode(),
                        'to_station_code'   => $this->trainParam->getToCode(),
                        'train_date'        => $this->trainParam->getStartAt(),
                        'train_code'        => $this->trainParam->getTripCode(),
                        'user_id'           => $this->param->getUserId(),
                        'order_sn'          => $this->param->getOriginOrderSn(),
                    ]);
                if ($list?->count() > 0) {
                    throw new Exception("不能改签到原行程", 62001);
                }
            }
        }

        // 所有用户的订单进行匹配
        $list = $this->trainOrderRepo
            ->checkSameTripTrainData([
                'from_station_code' => $this->trainParam->getFromCode(),
                'to_station_code'   => $this->trainParam->getToCode(),
                'train_date'        => $this->trainParam->getStartAt(),
                'train_code'        => $this->trainParam->getTripCode(),
            ]);

        foreach ($list as $item) {
            $passenger_name = collect($item->passengers)->whereIn('passenger_id', $this->passengersParam->getPassengerIds())->value('truename');
            if ($passenger_name) {
                Log::error("{$passenger_name} 行程已存在，请更换行程");
                throw new Exception("{$passenger_name}".__("行程已存在，请更换行程"), 62002);
            }
        }
        return true;
    }
}